package com.pig4cloud.pig.ads.gdt.service.impl;


import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONArray;
import com.alibaba.fastjson.JSONObject;
import com.alibaba.fastjson.TypeReference;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.core.toolkit.CollectionUtils;
import com.baomidou.mybatisplus.core.toolkit.Wrappers;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.google.api.client.util.Lists;
import com.pig4cloud.pig.ads.gdt.service.*;
import com.pig4cloud.pig.ads.pig.mapper.AdPicturePlatformMapper;
import com.pig4cloud.pig.ads.pig.mapper.gdt.GdtAdCreativeMapper;
import com.pig4cloud.pig.ads.pig.mapper.gdt.GdtAdCreativeTempMapper;
import com.pig4cloud.pig.ads.pig.mapper.gdt.GdtAdMapper;
import com.pig4cloud.pig.ads.service.AdCreativeMaterialService;
import com.pig4cloud.pig.ads.service.AdLandingPageService;
import com.pig4cloud.pig.ads.service.AdvService;
import com.pig4cloud.pig.ads.utils.HtmlRequest;
import com.pig4cloud.pig.ads.utils.ImgTagUtils;
import com.pig4cloud.pig.ads.utils.OEHttpUtils;
import com.pig4cloud.pig.api.entity.*;
import com.pig4cloud.pig.api.enums.GdtPageStatusEnum;
import com.pig4cloud.pig.api.gdt.dto.*;
import com.pig4cloud.pig.api.gdt.entity.*;
import com.pig4cloud.pig.common.core.constant.enums.PlatformTypeEnum;
import com.pig4cloud.pig.common.core.exception.CheckedException;
import com.pig4cloud.pig.api.enums.GdtAdEnum;
import com.pig4cloud.pig.api.enums.StatusEnum;
import com.pig4cloud.pig.api.gdt.vo.GdtAdCreativeVo;
import com.pig4cloud.pig.ads.clickhouse3399.mapper.GdtAdCreativeReportMapper;
import com.pig4cloud.pig.common.core.util.R;
import com.pig4cloud.pig.common.security.util.SecurityUtils;
import com.pig4cloud.pig.api.util.JsonUtil;
import com.pig4cloud.pig.api.util.MapUtils;
import lombok.extern.log4j.Log4j2;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import javax.annotation.Resource;
import java.net.URL;
import java.util.*;
import java.util.concurrent.*;
import java.util.stream.Collectors;

/**
 * 广点通广告创意 服务层实现
 *
 * @author hma
 * @date 2020-12-10
 */
@Log4j2
@Service
public class GdtAdCreativeServiceImpl extends ServiceImpl<GdtAdCreativeMapper, GdtAdCreative> implements IGdtAdCreativeService {

	@Resource
	private IGdtCampaignService gdtCampaignService;
	@Value(value = "${gdt_creative_templates_get_url}")
	private String creativeTemplatesUrl;
	@Value(value = "${gdt_creative_previews_url}")
	private String creativePreviewUrl;
	@Value(value = "${gdt_creative_add_url}")
	private String creativeAddUrl;

	@Value(value = "${gdt_dynamic_creative_add_url}")
	private String dynamicCreativeAddUrl;

	@Value(value = "${gdt_dynamic_creative_get_url}")
	private String dynamicCreativeGetUrl;

	//	@Value(value = "${spring.profiles.active}")
//	private String springProfilesActive;
	@Value(value = "${gdt.configured.status}")
	private String configuredStatus;

	@Value(value = "${gdt_ad_creative_get}")
	private String gdtAdCreativeGetUrl;

	@Value(value = "${gdt_ad_update_url}")
	private String gdtAdUpdateUrl;

	@Value(value = "${gdt_url}")
	private String gdtUrl;


	@Value(value = "${gdt_pages_get_url}")
	private String gdtPagesGetUrl;
	@Value(value = "${gdt_creativetools_text_url}")
	private String gdtCreativeToolsTextUrl;
	@Resource
	private AdCreativeMaterialService adCreativeMaterialService;
	@Resource
	private GdtAdMapper gdtAdMapper;

	@Resource
	private GdtAdCreativeMapper gdtAdCreativeMapper;

	@Resource
	private GdtAccesstokenService gdtAccesstokenService;

	@Resource
	private GdtAdCreativeTempMapper gdtAdCreativeTempMapper;
	@Resource
	private IGdtAdService gdtAdService;
	@Resource
	private IGdtAdgroupService gdtAdgroupService;
	@Resource
	private IGdtAdgroupTempService gdtAdgroupTempService;
	@Resource
	private GdtAdCreativeReportMapper gdtAdCreativeReportMapper;

	@Resource
	private AdPicturePlatformMapper adPicturePlatformMapper;
	@Resource
	private IGdtCampaignService campaignService;

	@Autowired
	private AdvService advService;

	@Resource
	private IGdtCreativeTemplatesService gdtCreativeTemplatesService;


	@Resource
	private GdtDynamicCreativeService gdtDynamicCreativeService;

	private ExecutorService es;

	@Autowired
	private AdLandingPageService adLandingPageService;

	/*
	 *  调广点通接口设置广告创意开关：广告开关configured_status
	 * */
	@Override
	public R updateGdtAdOnOff(GdtAdCreativeVo gdtAdCreativeVo) {

		String onOff = gdtAdCreativeVo.getOnOff();
		if (onOff == null || StringUtils.isBlank(onOff)) {
			return R.failed("请选择广告创意开关");
		}
		Long adcreativeId = gdtAdCreativeVo.getAdcreativeId();
		List<GdtAd> gdtAds = gdtAdMapper.selectList(Wrappers.<GdtAd>query().lambda()
				.eq(GdtAd::getAdcreativeId, adcreativeId));
		if (Objects.isNull(gdtAds) || gdtAds.size() <= 0) {
			return R.failed("该广告创意无广告计划使用！");
		}
		GdtAdCreative gdtAdCreative = gdtAdCreativeMapper.selectOne(Wrappers.<GdtAdCreative>query().lambda()
				.eq(GdtAdCreative::getAdcreativeId, adcreativeId).last("LIMIT 1"));
		String accountId = String.valueOf(gdtAdCreative.getAccountId());
		Map<String, String> map = gdtAccesstokenService.fetchAccesstoken(accountId);
		if (map == null || StringUtils.isEmpty(map.get("access_token"))) {
			return R.failed("广点通账户授权失败，请重试！");
		}
		//请求url
		String urlstr = gdtUrl + gdtAdUpdateUrl + "?" + MapUtils.queryString(map);
		log.info("修改广点通广告计划 request:" + urlstr);
		Map<String, Object> params = new HashMap<>();
		params.put("account_id", accountId);
		//默认为有效状态
		String configuredStatuType = GdtAdEnum.AD_STATUS_NORMAL.getType();
		if ("AD_STATUS_SUSPEND".equals(onOff)) {
			//暂停状态
			configuredStatuType = GdtAdEnum.AD_STATUS_SUSPEND.getType();
		}
		params.put("configured_status", configuredStatuType);

		//循环广告，调用广点通接口，修改开关状态
		for (int i = 0; i < gdtAds.size(); i++) {
			params.put("ad_id", gdtAds.get(i).getAdId());
			//提交请求广点通修改推广计划接口
			String resultStr = OEHttpUtils.doPost(urlstr, params);
			log.info("修改广点通ad开关： response:" + resultStr);
			ResponseBean resBean = JSON.parseObject(resultStr, ResponseBean.class);
			if (StringUtils.equals(resBean.getCode(), "0")) {
				//同步修改数据库(mysql+CH)
				//mysql
				gdtAds.get(i).setConfiguredStatus(configuredStatuType);
				QueryWrapper<GdtAd> queryWrapper = new QueryWrapper<GdtAd>();
				queryWrapper.eq("ad_id", gdtAds.get(i).getAdId());//条件：广告id
				gdtAdMapper.update(gdtAds.get(i), queryWrapper);//修改mysql中gdt_ad表的该广告id记录的configured_status字段
				//CH todo
			} else {
				return R.failed("修改开关状态失败!");
			}
		}

		return R.ok(null, "修改成功");
	}

	/*
	 *  查询广告创意列表数据
	 * */
	@Override
	public R getGdtAdCreativeReport(GdtAdCreativeVo gdtAdCreativeVo) {
		//获取当前账号下 广点通广告账户列表
		List<String> advertiserList = advService.getOwnerAdv(SecurityUtils.getUser().getId(), PlatformTypeEnum.GDT.getValue());
		if (null == advertiserList || advertiserList.size() <= 0) {
			return R.failed("未绑定广告账户，无法查看");
		}
		//设置参数:广告账户ids集合
		//前端没传广告账户参数，通过当前账户查询
		if (null == gdtAdCreativeVo.getAdvertiserIds() || gdtAdCreativeVo.getAdvertiserIds().length <= 0) {
			gdtAdCreativeVo.setAccountIds(advertiserList);
		} else {//前端有传广告账户参数
			List<String> advertiserIdsList = Arrays.asList(gdtAdCreativeVo.getAdvertiserIds());
			gdtAdCreativeVo.setAccountIds(advertiserIdsList);
		}
		//处理时间参数
		String sdate = gdtAdCreativeVo.getSdate();
		String edate = gdtAdCreativeVo.getEdate();
		if (StringUtils.isBlank(sdate) || StringUtils.isBlank(edate)) {
			return R.failed("时间参数异常");
		}
		gdtAdCreativeVo.setSdate(sdate);
		gdtAdCreativeVo.setEdate(edate);

		//广点通报表
		IPage<GdtAdCreativeReport> result = null;
		try {
			result = gdtAdCreativeReportMapper.selectGdtAdCreativeReport(gdtAdCreativeVo);
			List<GdtAdCreativeReport> records = result.getRecords();
			//查询图片url + onOff
			if (records.size() > 0) {
				for (int i = 0; i < records.size(); i++) {
					//1 预览：图片url
					String adcreativeElements = records.get(i).getAdcreativeElements();
					Map map = JSONObject.parseObject(adcreativeElements, Map.class);
					records.get(i).setImageUrl("");
					//设置imageUrl 空字符串
					String imageId = "";
					//如果adcreativeElements中包含image字符串
					if (adcreativeElements.contains("image") && !adcreativeElements.contains("image_list")) {
						imageId = (String) map.get("image");
					}
					if (adcreativeElements.contains("image_list")) {
						if (StringUtils.isNotBlank(map.get("image_list").toString())) {
							String[] image_list = ((JSONArray) map.get("image_list")).toArray(new String[]{});
							imageId = image_list[0];
						}
					}
					//设置imageUrl
					if (StringUtils.isNotBlank(imageId)) {
						//通过imageId查询图片url，预览
						AdPicturePlatform picPlatform = adPicturePlatformMapper.selectOne(Wrappers.<AdPicturePlatform>query().lambda()
								.eq(AdPicturePlatform::getPlatformId, 3)
								.eq(AdPicturePlatform::getPlatformPictureId, imageId)
								.last("LIMIT 1"));
						if (Objects.nonNull(picPlatform)) {
							records.get(i).setImageUrl(picPlatform.getPlatformPictureUrl());
						}
					}

					//2 设置开关状态：onOff
					Long adcreativeId = records.get(i).getAdcreativeId();
					GdtAd gdtAd = gdtAdMapper.selectOne(Wrappers.<GdtAd>query().lambda().eq(GdtAd::getAdcreativeId, adcreativeId).last("LIMIT 1"));
					if (null == gdtAd) {
						records.get(i).setOnOff(GdtAdEnum.AD_STATUS_SUSPEND.getType());//该广告创意下无广告记录
					} else {
						records.get(i).setOnOff(gdtAd.getConfiguredStatus());
					}

				}
			}
			//广告创意列表数据放回分页类中
			result.setRecords(records);
		} catch (Exception e) {
			e.printStackTrace();
		}
		return R.ok(result, "查询成功");
	}

	/**
	 * 创建创意
	 *
	 * @param creativeCreateDtoList
	 * @return
	 */
	@Override
	@Transactional(rollbackFor = Exception.class)
	public R createGdtCreativeTemp(List<GdtAdCreativeCreateDto> creativeCreateDtoList) {
		try {
			Integer userId = Objects.requireNonNull(SecurityUtils.getUser()).getId();
			List<String> creativeNameList = creativeCreateDtoList.stream().map(GdtAdCreativeTemp::getAdcreativeName).collect(Collectors.toList());
			long count = creativeNameList.stream().distinct().count();
			if (creativeNameList.size() > count) {
				return R.failed("多个创意名称不允许重复");
			}

			creativeCreateDtoList.forEach(creativeCreateDto -> {
				if (StringUtils.isNotBlank(creativeCreateDto.getSiteSets())) {
					creativeCreateDto.setSiteSet(creativeCreateDto.getSiteSets());
				}
				if (null != creativeCreateDto.getAdcreativeTemplateId() && 910L == creativeCreateDto.getAdcreativeTemplateId()) {
					creativeCreateDto.setPageType("PAGE_TYPE_TSA_APP");
					if (StringUtils.isBlank(creativeCreateDto.getPageSpec())) {
						throw new CheckedException("落地页不允许为空");
					}
				}
				creativeCreateDto.setUserId(userId.longValue());
				if (null != creativeCreateDto.getAdcreativeElementsObject()) {
					creativeCreateDto.setAdcreativeElements(JSONObject.toJSONString(creativeCreateDto.getAdcreativeElementsObject()));
				}
				if (null != creativeCreateDto.getAdgroupId()) {
					GdtAdgroupTemp gdtAdgroupTemp =	gdtAdgroupTempService.getCreateGdtGroupById(creativeCreateDto.getAdgroupId());
					if (gdtAdgroupTemp==null) {
						throw new CheckedException("当前广告组不存在");
					}
					if (!"1".equals(gdtAdgroupTemp.getAutomaticSiteEnabled())) {
						String siteSets = gdtAdgroupTemp.getSiteSet();
						if (StringUtils.isBlank(siteSets)) {
							//设置默认的投放版位--自动版位
							siteSets = "[\"SITE_SET_MOBILE_UNION\",\"SITE_SET_MOBILE_INNER\",\"SITE_SET_TENCENT_NEWS\",\"SITE_SET_TENCENT_VIDEO\",\"SITE_SET_KANDIAN\",\"SITE_SET_QQ_MUSIC_GAME\"]";
						} else if (JSONArray.parseArray(siteSets).size() < 1) {
							siteSets = "[\"SITE_SET_MOBILE_UNION\",\"SITE_SET_MOBILE_INNER\",\"SITE_SET_TENCENT_NEWS\",\"SITE_SET_TENCENT_VIDEO\",\"SITE_SET_KANDIAN\",\"SITE_SET_QQ_MUSIC_GAME\"]";
						}
						creativeCreateDto.setSiteSet(siteSets);
					} else {
						creativeCreateDto.setAutomaticSiteEnabled(true);
						if (gdtAdgroupTemp.getAutomaticSiteEnabled() != null) {
							creativeCreateDto.setAutomaticSiteEnabled("1".equals(gdtAdgroupTemp.getAutomaticSiteEnabled()));
						}
						creativeCreateDto.setSiteSet(null);
						creativeCreateDto.setSiteSets(null);
					}
				}
			});

			final List<GdtAdCreativeCreateDto> creativeCreateDtoListF = creativeCreateDtoList;

			List<GdtAdDto> gdtAdDtoList = new ArrayList<>();
			List<Long> creativeId = new ArrayList<>();
			//创建创意
			for (GdtAdCreativeCreateDto creativeCreateDtoF : creativeCreateDtoListF) {
				if("1".equals(creativeCreateDtoF.getIsDynamicCreative())&&creativeCreateDtoList.size()>3) {
					throw new CheckedException("动态创意最多创建三组");
				}
				gdtAdCreativeTempMapper.insert(creativeCreateDtoF);
				this.createGdtCreative(creativeCreateDtoF);
				if("1".equals(creativeCreateDtoF.getIsDynamicCreative())) {
					creativeId.add(creativeCreateDtoF.getAdcreativeId());
				}
			}
			//创建广告组
			GdtAdgroupCreateTempDto adgroup = gdtAdgroupTempService.createGdtGroup(creativeCreateDtoListF.get(0),creativeId);

			//创建广告
			for (GdtAdCreativeCreateDto creativeCreateDtoF : creativeCreateDtoListF) {
				String impressionTrackingUrl = null;
				String clickTrackingUrl = null;
				String feedsInteractionEnabled = null;
				GdtAdDto gdtAdDto = new GdtAdDto(creativeCreateDtoF.getAccountId().toString(), creativeCreateDtoF.getCampaignId(), adgroup.getAdgroupId(), creativeCreateDtoF.getAdcreativeId()
						, creativeCreateDtoF.getAdcreativeName(), configuredStatus, impressionTrackingUrl, clickTrackingUrl, feedsInteractionEnabled);
				//建创广告
				if(!"1".equals(creativeCreateDtoF.getIsDynamicCreative())) {
					gdtAdService.createGdtAd(gdtAdDto);
					gdtAdDtoList.add(gdtAdDto);
				}else {
					gdtAdDto.setIsDynamicCreative("1");
				}
			}
			if (CollectionUtils.isNotEmpty(gdtAdDtoList)) {
				es = new ThreadPoolExecutor(5, 5, 10, TimeUnit.SECONDS, new ArrayBlockingQueue<>(50));
				es.submit(() -> {
					try {
						// 拉取数据存储,广告创意，广告
						GdtAdDto gdtAdDtoF =  new GdtAdDto();
						gdtAdDtoF.setAccountId(adgroup.getAccountId());
						if(!"1".equals(gdtAdDtoF.getIsDynamicCreative())) {
							gdtAdDtoF = gdtAdDtoList.get(0);
							if (gdtAdDtoList.size() > 1) {
								String adIds = gdtAdDtoList.stream().map(gdtAdDto -> gdtAdDto.getAdId().toString()).collect(Collectors.joining(","));
								gdtAdDtoF.setAdIds(adIds);
								gdtAdDtoF.setAdId(null);
								String adCreativeIds = gdtAdDtoList.stream().map(gdtAdDto -> gdtAdDto.getAdcreativeId().toString()).collect(Collectors.joining(","));
								gdtAdDtoF.setAdcreativeIds(adCreativeIds);
								gdtAdDtoF.setAdcreativeId(null);
							}
							gdtAdDtoF.setAdgroupId(null);
							//拉取广告
							gdtAdService.getGdtAdData(gdtAdDtoF);
						}else {
							gdtAdDtoF.setAdcreativeIds(creativeId.stream().map(Object::toString).collect(Collectors.joining(",")));
						}
						//拉取创意
						this.getAdCreativeData(gdtAdDtoF,"1".equals(gdtAdDtoF.getIsDynamicCreative()));
					} catch (Exception e) {
						log.error("createGdtCreativeTemp is error", e);
					}
				});
			}

			return R.ok(gdtAdDtoList);
		} catch (Exception e) {
			log.error("createGdtCreativeTemp is error", e);
			String messsage = e.getMessage();
			if (StringUtils.isNotBlank(messsage)) {
				if (messsage.contains("BusinessException:")) {
					String substring0 = messsage.substring(0, messsage.indexOf(":"));
					messsage = messsage.substring(substring0.length() + 1);
				}

			} else {
				messsage = "服务器异常，请稍后重试";
			}
			return R.failed(messsage);
		}

	}


	/**
	 * 创建广创意--调用三方
	 *
	 * @param creativeCreateDto
	 * @return
	 */
	@Override
	public GdtAdCreativeCreateDto createGdtCreative(GdtAdCreativeCreateDto creativeCreateDto) {
		try {
			if (StringUtils.isBlank(creativeCreateDto.getPageType())) {
				creativeCreateDto.setPageType("PAGE_TYPE_DEFAULT");
			}
			if (StringUtils.isNotBlank(creativeCreateDto.getPageSpec())) {
				//由于使用了@JsonInclude(JsonInclude.Include.NON_NULL)，需要转一下去掉为null的值
				JSONObject jsonObject = JSONObject.parseObject(creativeCreateDto.getPageSpec());
				creativeCreateDto.setPageSpec(jsonObject.toJSONString());
			}
			creativeCreateDto.setAdcreativeElementsObject(null);
			if (null != creativeCreateDto.getAdcreativeElements()) {
				JSONObject jsonObject = JSONObject.parseObject(creativeCreateDto.getAdcreativeElements());
				creativeCreateDto.setAdcreativeElements(jsonObject.toJSONString());

			}
			if (creativeCreateDto.getDynamicAdcreativeSpec() != null) {
				JSONObject jsonObject = JSONObject.parseObject(creativeCreateDto.getDynamicAdcreativeSpec());
				creativeCreateDto.setDynamicAdcreativeSpec(jsonObject.toJSONString());

			}
			Map<String, Object> param = JsonUtil.parseJSON2Map(JsonUtil.toUnderlineJSONString(creativeCreateDto));
			JSONObject jsonObject;
			if(!"1".equals(creativeCreateDto.getIsDynamicCreative())){
				jsonObject= gdtCampaignService.createOrGetPostThirdResponse(creativeCreateDto.getAccountId().toString(), "createGdtCreative", creativeAddUrl, param);
			}else {
				param.put("dynamic_creative_name",creativeCreateDto.getAdcreativeName());
				param.put("dynamic_creative_template_id",creativeCreateDto.getAdcreativeTemplateId());
				param.put("dynamic_creative_elements",creativeCreateDto.getAdcreativeElements());
				param.put("campaign_type","CAMPAIGN_TYPE_NORMAL");
				jsonObject= gdtCampaignService.createOrGetPostThirdResponse(creativeCreateDto.getAccountId().toString(), "createGdtDynamicCreative", dynamicCreativeAddUrl, param);
			}

			if (null != jsonObject) {
				if(!"1".equals(creativeCreateDto.getIsDynamicCreative())) {
					creativeCreateDto.setAdcreativeId(jsonObject.getLong("adcreative_id"));
				}else {
					creativeCreateDto.setAdcreativeId(jsonObject.getLong("dynamic_creative_id"));
				}
			}
			return creativeCreateDto;
		} catch (Exception e) {
			log.error("createGdtCreative is error", e);
			throw new CheckedException(e.getMessage());
		}

	}


	/**
	 * 获取广告创意形式/创意 内容----------优化【拆解合并】
	 *
	 * @param gdtAdCreativeDto
	 * @return
	 */
	@Override
	public R getCreativeTemplatesUpdate(GdtAdCreativeDto gdtAdCreativeDto, String fields, Integer operateType) {
		try {
			if (StringUtils.isBlank(gdtAdCreativeDto.getPromotedObjectType())) {
				//推广目标为空，查询推广列表获取推广计划对应的推广目标
				List<GdtCampaign> gdtCampaignList = gdtCampaignService.gdtCampaignList(new GdtCampaign(gdtAdCreativeDto.getCampaignId()));
				if (CollectionUtils.isEmpty(gdtCampaignList)) {
					return R.failed("当前推广计划不存在");
				}
				gdtAdCreativeDto.setPromotedObjectType(gdtCampaignList.get(0).getPromotedObjectType());
			}
			JSONArray jsonArray = JSON.parseArray(gdtAdCreativeDto.getSiteSets());
			Object[] siteSitArr = null;
			if (CollectionUtils.isNotEmpty(jsonArray)) {
				siteSitArr = jsonArray.toArray();

			}
			gdtAdCreativeDto.setIsDynamicCreative(StringUtils.isBlank(gdtAdCreativeDto.getIsDynamicCreative())||"0".equals(gdtAdCreativeDto.getIsDynamicCreative())? "false":"true");

			GdtCreativeTemplates gdtCreativeTemplatesnew = new  GdtCreativeTemplates(gdtAdCreativeDto.getPromotedObjectType(), siteSitArr, gdtAdCreativeDto.getAdcreativeTemplateId(), StatusEnum.TYPE_ONE.getStatus(),gdtAdCreativeDto.getIsDynamicCreative(),gdtAdCreativeDto.getAccountId());
			gdtCreativeTemplatesnew.setSupportBidModeList(gdtAdCreativeDto.getBidMode());
			//查询标准化创意
			List<GdtCreativeTemplates> gdtCreativeTemplatesList = gdtCreativeTemplatesService.selectGdtCreativeTemplates(gdtCreativeTemplatesnew);
			List<GdtCreativeTemplates> maxLengthGdtCreativeTemplates = new ArrayList<>();
			if (CollectionUtils.isNotEmpty(gdtCreativeTemplatesList)) {
				gdtCreativeTemplatesList.forEach(gdtCreativeTemplates -> {
					gdtCreativeTemplates.setLength(gdtCreativeTemplates.getAdcreativeElements().length());
				});
				gdtCreativeTemplatesList = gdtCreativeTemplatesList.stream().sorted(Comparator.comparing(GdtCreativeTemplates::getLength).reversed()).collect(Collectors.toList());
				Map<Object, List<GdtCreativeTemplates>> longListMap = null;
				if (StatusEnum.TYPE_ONE.getStatus().equals(operateType)) {
					//查询广告版位
					longListMap = gdtCreativeTemplatesList.stream().collect(Collectors.groupingBy(GdtCreativeTemplates::getSiteSet));
				} else if (StatusEnum.TYPE_TWO.getStatus().equals(operateType)) {
					//查询出价版位
					longListMap = gdtCreativeTemplatesList.stream().collect(Collectors.groupingBy(GdtCreativeTemplates::getSupportBidModeList));

				} else {
					//查询创意形式
					//gdtCreativeTemplatesList = gdtCreativeTemplatesList.stream().filter(a -> a.getSupportBidModeList().contains(gdtAdCreativeDto.getBidMode())).collect(Collectors.toList());
					//将对应的创意元素内容进行拆了然后合并，并集

					longListMap = gdtCreativeTemplatesList.stream().collect(Collectors.groupingBy(GdtCreativeTemplates::getAdcreativeTemplateId));
					longListMap.forEach((key, value) -> {
						if (CollectionUtils.isNotEmpty(value)) {
							if (null != jsonArray && jsonArray.size() == 1) {
								maxLengthGdtCreativeTemplates.add(value.get(0));
							} else {
								if (value.size() > 1) {
									List<Map<String, Object>> mapList = new ArrayList<>();
									value.forEach(gdtCreativeTemplates -> {
										List<Map<String, Object>> listMap = JSON.parseObject(gdtCreativeTemplates.getAdcreativeElements(), new TypeReference<List<Map<String, Object>>>() {
										});
										mapList.addAll(listMap);
									});
									GdtCreativeTemplates resultTemplate = value.get(0);
									if (CollectionUtils.isNotEmpty(mapList)) {
										List<Map<String, Object>> distinctMapList = new ArrayList<Map<String, Object>>();
										distinctMapList = mapList.stream().collect(Collectors.collectingAndThen(Collectors.toCollection(() -> new TreeSet<Map<String, Object>>(Comparator.comparing(o -> o.get("name").toString()))), ArrayList::new));
										resultTemplate.setAdcreativeElements(JSONArray.toJSONString(distinctMapList));
									}
									maxLengthGdtCreativeTemplates.add(resultTemplate);

								} else {
									maxLengthGdtCreativeTemplates.add(value.get(0));
								}
							}

						} else {

						}
					});

					maxLengthGdtCreativeTemplates.forEach(gdtCreativeTemplates -> {
						List<Map<String, Object>> listMap = JSON.parseObject(gdtCreativeTemplates.getAdcreativeElements(), new TypeReference<List<Map<String, Object>>>() {
						});
						listMap = listMap.stream().sorted(Comparator.comparing(o -> o.get("description").toString().length())).collect(Collectors.toList());
						gdtCreativeTemplates.setAdcreativeElements(JSONArray.toJSONString(listMap));
					});
					List<GdtCreativeTemplates> resultTemplates = maxLengthGdtCreativeTemplates.stream()
							.filter(a->a.getSupportPageType().contains("\"PAGE_TYPE_DEFAULT\"")||a.getSupportPageType().contains("\"PAGE_TYPE_TSA_APP\"")||a.getSupportPageType().contains("\"PAGE_TYPE_XIJING_QUICK\""))
							.sorted(Comparator.comparing(GdtCreativeTemplates::getAdcreativeTemplateId)).collect(Collectors.toList());
					return R.ok(resultTemplates);
				}

				longListMap.forEach((key, value) -> {
					if (CollectionUtils.isNotEmpty(value)) {
						maxLengthGdtCreativeTemplates.add(value.get(0));
					}
				});
			}
			List<GdtCreativeTemplates> resultTemplates = maxLengthGdtCreativeTemplates.stream()
					.filter(a->a.getSupportPageType().contains("\"PAGE_TYPE_DEFAULT\"")||a.getSupportPageType().contains("\"PAGE_TYPE_TSA_APP\"")||a.getSupportPageType().contains("\"PAGE_TYPE_XIJING_QUICK\""))
					.sorted(Comparator.comparing(GdtCreativeTemplates::getAdcreativeTemplateId)).collect(Collectors.toList());



			return R.ok(resultTemplates);
		} catch (Exception e) {
			log.error("getCreativeTemplates  toSnakeObject is error", e);
			throw new CheckedException(e.getMessage());
		}

	}

	/**
	 * 获取广告创意形式/创意 内容
	 *
	 * @param gdtAdCreativeDto
	 * @return
	 */
	@Override
	public R getCreativeTemplates(GdtAdCreativeDto gdtAdCreativeDto, String fields, Integer operateType) {
		try {
			if (StringUtils.isBlank(gdtAdCreativeDto.getPromotedObjectType())) {
				//推广目标为空，查询推广列表获取推广计划对应的推广目标
				List<GdtCampaign> gdtCampaignList = gdtCampaignService.gdtCampaignList(new GdtCampaign(gdtAdCreativeDto.getCampaignId()));
				if (CollectionUtils.isEmpty(gdtCampaignList)) {
					return R.failed("当前推广计划不存在");
				}
				gdtAdCreativeDto.setPromotedObjectType(gdtCampaignList.get(0).getPromotedObjectType());
			}
			JSONArray jsonArray = JSON.parseArray(gdtAdCreativeDto.getSiteSets());
			Object[] siteSitArr = null;
			if (CollectionUtils.isNotEmpty(jsonArray)) {
				siteSitArr = jsonArray.toArray();

			}


			//查询标准化创意
			List<GdtCreativeTemplates> gdtCreativeTemplatesList = gdtCreativeTemplatesService.selectGdtCreativeTemplates(new GdtCreativeTemplates(gdtAdCreativeDto.getPromotedObjectType(), siteSitArr, gdtAdCreativeDto.getAdcreativeTemplateId(), StatusEnum.TYPE_ONE.getStatus(),null,gdtAdCreativeDto.getAccountId()));
			List<GdtCreativeTemplates> maxLengthGdtCreativeTemplates = new ArrayList<>();
			if (CollectionUtils.isNotEmpty(gdtCreativeTemplatesList)) {
				gdtCreativeTemplatesList.forEach(gdtCreativeTemplates -> {
					gdtCreativeTemplates.setLength(gdtCreativeTemplates.getAdcreativeElements().length());
				});
				gdtCreativeTemplatesList = gdtCreativeTemplatesList.stream().sorted(Comparator.comparing(GdtCreativeTemplates::getLength).reversed()).collect(Collectors.toList());
				Map<Object, List<GdtCreativeTemplates>> longListMap = null;
				if (StatusEnum.TYPE_ONE.getStatus().equals(operateType)) {
					//查询广告版位
					longListMap = gdtCreativeTemplatesList.stream().collect(Collectors.groupingBy(GdtCreativeTemplates::getSiteSet));
				} else if (StatusEnum.TYPE_TWO.getStatus().equals(operateType)) {
					//查询出价版位
					longListMap = gdtCreativeTemplatesList.stream().collect(Collectors.groupingBy(GdtCreativeTemplates::getSupportBidModeList));

				} else {
					//查询创意形式
					gdtCreativeTemplatesList = gdtCreativeTemplatesList.stream().filter(a -> a.getSupportBidModeList().contains(gdtAdCreativeDto.getBidMode())).collect(Collectors.toList());
					//将对应的创意元素内容进行拆了然后合并，并集
					longListMap = gdtCreativeTemplatesList.stream().collect(Collectors.groupingBy(GdtCreativeTemplates::getAdcreativeTemplateId));
					longListMap.forEach((key, value) -> {
						if (CollectionUtils.isNotEmpty(value)) {
							if (value.size() > 1) {
								if (null != jsonArray && jsonArray.size() > 1) {
									if (jsonArray.contains("SITE_SET_QQ_MUSIC_GAME") && jsonArray.contains("SITE_SET_KANDIAN") && jsonArray.size() == 2) {
										maxLengthGdtCreativeTemplates.add(value.get(0));
									} else {
										List<GdtCreativeTemplates> unionResult = value.stream().filter(t -> t.getSiteSet().equals("SITE_SET_MOBILE_UNION")).collect(Collectors.toList());
										if (CollectionUtils.isNotEmpty(unionResult)) {
											maxLengthGdtCreativeTemplates.add(unionResult.get(0));
										} else {
											Boolean flagA = Boolean.FALSE;
											Boolean flagB = Boolean.FALSE;
											if (jsonArray.contains("SITE_SET_QQ_MUSIC_GAME") || jsonArray.contains("SITE_SET_KANDIAN")) {
												flagA = Boolean.TRUE;
											}
											if (jsonArray.contains("SITE_SET_TENCENT_VIDEO") || jsonArray.contains("SITE_SET_TENCENT_NEWS")) {
												flagB = Boolean.TRUE;
											}
											if (flagA && flagB) {
												//-合并数据【查询优良汇还是 有出入】
												List<Map<String, Object>> mapList = new ArrayList<>();
												value.forEach(gdtCreativeTemplates -> {
													List<Map<String, Object>> listMap = JSON.parseObject(gdtCreativeTemplates.getAdcreativeElements(), new TypeReference<List<Map<String, Object>>>() {
													});
													listMap = listMap.stream().sorted(Comparator.comparing(o -> o.get("description").toString().length())).collect(Collectors.toList());
													mapList.addAll(listMap);

												});
												List<Map<String, Object>> distinctMapList = mapList.stream().collect(Collectors.collectingAndThen(Collectors.toCollection(() -> new TreeSet<Map<String, Object>>(Comparator.comparing(o -> o.get("name").toString()))), ArrayList::new));
												GdtCreativeTemplates resultTemplate = value.get(0);
												resultTemplate.setAdcreativeElements(JSONArray.toJSONString(distinctMapList));
												maxLengthGdtCreativeTemplates.add(resultTemplate);
											} else {
												List<GdtCreativeTemplates> result = value.stream().filter(t -> !t.getSiteSet().equals("SITE_SET_QQ_MUSIC_GAME") && !t.getSiteSet().equals("SITE_SET_KANDIAN")).collect(Collectors.toList());
												if (CollectionUtils.isNotEmpty(result)) {
													maxLengthGdtCreativeTemplates.add(result.get(0));
												} else {
													maxLengthGdtCreativeTemplates.add(value.get(0));
												}

											}

										}

									}
								}
							} else {
								maxLengthGdtCreativeTemplates.add(value.get(0));
							}

						}
					});

					maxLengthGdtCreativeTemplates.forEach(gdtCreativeTemplates -> {
						List<Map<String, Object>> listMap = JSON.parseObject(gdtCreativeTemplates.getAdcreativeElements(), new TypeReference<List<Map<String, Object>>>() {
						});
						listMap = listMap.stream().sorted(Comparator.comparing(o -> o.get("description").toString().length())).collect(Collectors.toList());
						gdtCreativeTemplates.setAdcreativeElements(JSONArray.toJSONString(listMap));
					});
					List<GdtCreativeTemplates> resultTemplates = maxLengthGdtCreativeTemplates.stream().sorted(Comparator.comparing(GdtCreativeTemplates::getAdcreativeTemplateId)).collect(Collectors.toList());
					return R.ok(resultTemplates);
				}

				longListMap.forEach((key, value) -> {
					if (CollectionUtils.isNotEmpty(value)) {
						maxLengthGdtCreativeTemplates.add(value.get(0));
					}
				});
			}
			List<GdtCreativeTemplates> resultTemplates = maxLengthGdtCreativeTemplates.stream().sorted(Comparator.comparing(GdtCreativeTemplates::getAdcreativeTemplateId)).collect(Collectors.toList());
			return R.ok(resultTemplates);
		} catch (Exception e) {
			log.error("getCreativeTemplates  toSnakeObject is error", e);
			throw new CheckedException(e.getMessage());
		}

	}

	/**
	 * 创意预览
	 *
	 * @param gdtAdCreativeDto
	 * @return
	 */
	@Override
	public R creativePreviews(GdtAdCreativeDto gdtAdCreativeDto) {
		Map<String, Object> paramMap = new HashMap<>();
		paramMap.put("account_id", gdtAdCreativeDto.getAccountId());
		//正对已创建的广告预览效果
		if (StringUtils.isNotBlank(gdtAdCreativeDto.getAdIds())) {
			paramMap.put("ad_id_list", gdtAdCreativeDto.getAdIds().split(","));
		}
		if (StatusEnum.TYPE_ONE.getStatus().equals(gdtAdCreativeDto.getType())) {
			paramMap.put("adgroup_id", gdtAdCreativeDto.getAdgroupId());
		} else {
			GdtAdgroupTemp gdtAdgroupTemp = gdtAdgroupTempService.getOne(new QueryWrapper<>(new GdtAdgroupTemp(gdtAdCreativeDto.getAdgroupId())));
			if (null == gdtAdgroupTemp) {
				return R.failed("当前广告组不存在");
			}
			Map<String, Object> adGroupMap = new HashMap<>();
			adGroupMap.put("campaign_type", gdtAdgroupTemp.getCampaignType());
			//默认安装下载 预览
			String billEvent = "BILLINGEVENT_APP_DOWNLOAD";
			if (StringUtils.isNotBlank(gdtAdgroupTemp.getBillingEvent())) {
				billEvent = gdtAdgroupTemp.getBillingEvent();
			}
			adGroupMap.put("billing_event", billEvent);
			adGroupMap.put("campaign_type", gdtAdgroupTemp.getCampaignType());
			adGroupMap.put("promoted_object_type", gdtAdgroupTemp.getPromotedObjectType());
			adGroupMap.put("promoted_object_id", gdtAdgroupTemp.getPromotedObjectId());
			paramMap.put("adgroup", adGroupMap);

			List<Map<String, Object>> adList = new ArrayList<>();
			CreativeContentDto creativeContentDto = new CreativeContentDto();
			if (StringUtils.isNotBlank(gdtAdCreativeDto.getAdCreative())) {
				creativeContentDto = JSONObject.parseObject(gdtAdCreativeDto.getAdCreative(), CreativeContentDto.class);
			} else {
				//TODO  对应的测试数据
				creativeContentDto.setAdcreativeName("创意预览");
				creativeContentDto.setPageType("PAGE_TYPE_DEFAULT");
				creativeContentDto.setAdcreativeTemplateId(711L);
				String creativeEle = "{\"image\":\"66159322\",\"description\":\"66666666666\",\"label\":[{\"content\":\"《推荐》\"}],\"title\":\"132456\",\"brand\":{\"brand_name\":\"冒险世界\",\"brand_img\":\"66160154\"}}";
				JSONObject jsonObject = JSON.parseObject(creativeEle);
				creativeContentDto.setAdcreativeElements(JSONObject.toJSONString(jsonObject));
			}
			Map<String, Object> adMap = new HashMap<>();
			adMap.put("ad_name", gdtAdgroupTemp.getAdgroupName());
			Map<String, Object> adCreativeMap = new HashMap<>();
			if (StringUtils.isBlank(creativeContentDto.getAdcreativeName())) {
				return R.failed("创意元素里面的创意名称不存在");
			}
			adCreativeMap.put("adcreative_name", creativeContentDto.getAdcreativeName());
			if (null == creativeContentDto.getAdcreativeTemplateId()) {
				return R.failed("创意元素里面的创意形式不允许为空");
			}
			adCreativeMap.put("adcreative_template_id", creativeContentDto.getAdcreativeTemplateId());
			if (StringUtils.isBlank(creativeContentDto.getAdcreativeElements())) {
				return R.failed("创意元素里面的创意内容不允许为空");
			}
			adCreativeMap.put("adcreative_elements", creativeContentDto.getAdcreativeElements());
			if ("1".equals(gdtAdgroupTemp.getAutomaticSiteEnabled())) {
				gdtAdgroupTemp.setSiteSet(JSONArray.toJSONString("SITE_SET_MOBILE_UNION,SITE_SET_MOBILE_INNER,SITE_SET_TENCENT_NEWS,SITE_SET_TENCENT_VIDEO,SITE_SET_KANDIAN,SITE_SET_QQ_MUSIC_GAME".split(",")));
			}
			adCreativeMap.put("site_set", gdtAdgroupTemp.getSiteSet());
			adCreativeMap.put("promoted_object_type", gdtAdgroupTemp.getPromotedObjectType());
			adCreativeMap.put("promoted_object_id", gdtAdgroupTemp.getPromotedObjectId());
			if (StringUtils.isBlank(creativeContentDto.getPageType())) {
				return R.failed("创意元素里面的落地页类型不存在");
			}
			if (StringUtils.isNotBlank(creativeContentDto.getPageSpec())) {
				adCreativeMap.put("page_spec", creativeContentDto.getPageSpec());
			}
			adMap.put("adcreative", adCreativeMap);

			adList.add(adMap);
			if (adList.size() > 0) {
				paramMap.put("ad_list", adList);
			}
		}
		//todo  对应的广告内容:广告名称，创意对应的内容
//		paramMap.put("ad_list",gdtAdCreativeDto.getAdgroupId());
		//创意预览
		JSONObject jsonObject = gdtCampaignService.createOrGetPostThirdResponse(gdtAdCreativeDto.getAccountId(), "creativePreviews", creativePreviewUrl, paramMap);
		if (CollectionUtils.isNotEmpty(jsonObject)) {
			//todo  字典替换
			String previewUrl = jsonObject.getString("preview_url");
			return R.ok(previewUrl);
		} else {
			return R.failed("当前创意无法预览");
		}


	}


	/**
	 * 查询按钮文案下拉框内容
	 *
	 * @return
	 */
	@Override
	public R getButtonText() {
		//todo 通过字段表存储查询，避免因变动修改代码

		String[] buttonTextArr = "去看看,下载,了解详情,参与活动,领取优惠,立即申请,立刻抢购,立即领取,立即体验,立即加入,获取报价,点击咨询".split(",");
		return R.ok(buttonTextArr);
	}




	/**
	 * 拉取广告创意并存储
	 *
	 * @param gdtAdDto
	 */
	@Override
	public void getAdCreativeData(GdtAdDto gdtAdDto) {
		getAdCreativeData( gdtAdDto,false);
	}
	/**
	 * 拉取广告创意并存储
	 *
	 * @param gdtAdDto
	 */
	@Transactional(rollbackFor = Exception.class)
	@Override
	public void getAdCreativeData(GdtAdDto gdtAdDto,boolean isDyCreative) {
		List<FilteringDto> filteringDtos = new ArrayList<>();
		String adcreativeIdStr = isDyCreative?"dynamic_creative_id":"adcreative_id";
		if (null != gdtAdDto.getAdcreativeIds()) {
			filteringDtos.add(new FilteringDto(adcreativeIdStr, "IN", gdtAdDto.getAdcreativeIds().split(",")));
		} else if (null != gdtAdDto.getAdcreativeId()) {
			filteringDtos.add(new FilteringDto(adcreativeIdStr, "EQUALS", gdtAdDto.getAdcreativeId().toString().split(",")));
		}
		if(!isDyCreative) {
			String fields = "campaign_id,adcreative_id,adcreative_name,adcreative_template_id,adcreative_elements,page_type,page_spec,link_page_type,link_name_type,link_page_spec,conversion_data_type,conversion_target_type,qq_mini_game_tracking_query_string,deep_link_url,android_deep_link_app_id,ios_deep_link_app_id,universal_link_url,site_set,automatic_site_enabled,promoted_object_type,promoted_object_id,profile_id,created_time,last_modified_time,share_content_spec,dynamic_adcreative_spec,is_deleted,is_dynamic_creative,multi_share_optimization_enabled,component_id,online_enabled,revised_adcreative_spec,category,label,union_market_switch,playable_page_material_id,video_end_page,webview_url,simple_canvas_sub_type,floating_zone,marketing_pendant_image_id,countdown_switch";
			List<JSONArray> jsonArrayList = campaignService.getThirdResponse(gdtAdDto.getAccountId(), "getAdCreativeData", gdtAdCreativeGetUrl, filteringDtos, null, fields, Boolean.TRUE);
			if (CollectionUtils.isNotEmpty(jsonArrayList)) {
				List<Map<String, String>> listMap = JSON.parseObject(jsonArrayList.get(0).toJSONString(), new TypeReference<List<Map<String, String>>>() {});
				List<GdtAdCreative> gdtAdCreativeList = JSONObject.parseArray(JSON.toJSONString(listMap), GdtAdCreative.class);
				if (CollectionUtils.isNotEmpty(gdtAdCreativeList)) {
					gdtAdCreativeList.forEach(gdtAdCreative -> gdtAdCreative.setAccountId(Long.valueOf(gdtAdDto.getAccountId())));
					this.saveOrUpdateBatch(gdtAdCreativeList);
				}
			}
		}else {
			//拉取动态创意保存
			String fields = "dynamic_creative_id,outer_adcreative_id,dynamic_creative_name,dynamic_creative_template_id,dynamic_creative_elements,page_type,page_spec,deep_link_url,automatic_site_enabled,site_set,promoted_object_type,promoted_object_id,profile_id,created_time,last_modified_time,dynamic_adcreative_spec,is_deleted,campaign_type,impression_tracking_url,click_tracking_url,feeds_video_comment_switch,union_market_switch,video_end_page,barrage_list,dynamic_creative_group_used,app_gift_pack_code,enable_breakthrough_siteset,creative_template_version_type,union_market_spec,creative_template_category,head_click_type,head_click_spec";
			List<JSONArray> jsonArrayList = campaignService.getThirdResponse(gdtAdDto.getAccountId(), "getAdDynamicCreativeData", dynamicCreativeGetUrl, filteringDtos, null, fields, Boolean.TRUE);
			if (CollectionUtils.isNotEmpty(jsonArrayList)) {
				List<Map<String, String>> listMap = JSON.parseObject(jsonArrayList.get(0).toJSONString(), new TypeReference<List<Map<String, String>>>() {});
				List<GdtDynamicCreative> gdtDynamicCreativeList = JSONObject.parseArray(JSON.toJSONString(listMap), GdtDynamicCreative.class);
				if (CollectionUtils.isNotEmpty(gdtDynamicCreativeList)) {
					gdtDynamicCreativeList.forEach(a -> {
						a.setAccountId(Long.valueOf(gdtAdDto.getAccountId()));
						a.setSoucreStatus(1);
					});
					gdtDynamicCreativeService.saveOrUpdateList(gdtDynamicCreativeList);
				}
			}

		}

	}



	/**
	 * 获取落地页
	 *
	 * @param gdtAdgroupTempDto
	 */
	@Override
	public R getGdtPage(GdtAdgroupTempDto gdtAdgroupTempDto) {
		LambdaQueryWrapper<AdLandingPage> query = new LambdaQueryWrapper<>();
		query.and(wrapper -> wrapper.in(AdLandingPage::getStatus,new String[]{"LANDING_PAGE_STATUS_PENDING","LANDING_PAGE_STATUS_APPROVED"})
				.eq(AdLandingPage::getPlatformId,PlatformTypeEnum.GDT.getValue())
				.eq(AdLandingPage::getAdvertiserId,gdtAdgroupTempDto.getAccountId()));
		if(StringUtils.isNotBlank(gdtAdgroupTempDto.getPageType())) {
			query.and(wrapper -> wrapper.eq(AdLandingPage::getPlayableType, gdtAdgroupTempDto.getPageType()));
		}
		List<AdLandingPage> adLandingPageList = adLandingPageService.list(query);
		List<GdtXlpDto> gdtXlpList = Lists.newArrayList();
		adLandingPageList.forEach(v ->{
			GdtXlpDto xlp = new GdtXlpDto();
			xlp.setPageName(v.getPageName());
			xlp.setPagePublishStatus(v.getPublishStatus());
			xlp.setPageStatus(v.getStatus());
			xlp.setPreviewUrl(v.getPageUrl());
			xlp.setPageId(v.getPageServiceId());
			xlp.setPageStatusName(GdtPageStatusEnum.nameByType(v.getStatus()));
			xlp.setPageType(v.getPlayableType());
			gdtXlpList.add(xlp);
		});
		return R.ok(gdtXlpList);
	}

	/**
	 * 查询广告文案
	 *
	 * @param creativetoolsDto
	 * @return
	 */
	@Override
	public R getCreativetoolsText(CreativetoolsDto creativetoolsDto) {
		int i = 0;
		while (i < 3) {
			i++;
			try {
				R r = R.ok();
				Map<String, String> paramMap = new HashMap<>();
				paramMap.put("max_text_length", creativetoolsDto.getMaxTextLength().toString());
				Optional.ofNullable(creativetoolsDto.getCategoryFirstLevel()).ifPresent(p -> paramMap.put("category_first_level", p.toString()));
				Optional.ofNullable(creativetoolsDto.getCategorySecondLevel()).ifPresent(p -> paramMap.put("category_second_level", p.toString()));
				Optional.ofNullable(creativetoolsDto.getKeyword()).ifPresent(p -> paramMap.put("keyword", p));
				paramMap.put("filtering", JSONArray.toJSONString("0,1".split(",")));
				paramMap.put("number", "200");
				String fields = null;
				List<JSONArray> jsonArrayList = campaignService.getThirdResponse(creativetoolsDto.getAccountId().toString(), "getCreativetoolsText", gdtCreativeToolsTextUrl, null, paramMap, fields, Boolean.FALSE);
				if (CollectionUtils.isNotEmpty(jsonArrayList)) {
					List<Map<String, String>> resultList = new ArrayList<>();
					jsonArrayList.forEach(jsonArr -> {
						jsonArr.forEach(jsonObject -> {
							JSONObject jsonObj = JSONObject.parseObject(jsonObject.toString());
							List<Map<String, String>> listMap = JSON.parseObject(jsonObj.getString("return_texts"), new TypeReference<List<Map<String, String>>>() {
							});
							resultList.addAll(listMap);
						});
					});

					if (CollectionUtils.isNotEmpty(resultList)) {
						r.setData(resultList);
					}
				}
				return r;
			} catch (Throwable e) {
				log.error("拉取广告文案失败次数={}", i);
			}
		}
		return R.failed("第三方调用失败");
	}
}
